package cn.iocoder.yudao.module.handguard.service.order;

import cn.iocoder.yudao.module.handguard.controller.admin.productaccesspercentage.vo.PercentageVO;
import cn.iocoder.yudao.module.handguard.controller.admin.statistics.vo.PerformanceStatisticsResVO;
import cn.iocoder.yudao.module.handguard.controller.app.carrecord.vo.CarRecordBaseVO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationdeductrecord.ApplicationDeductRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationrecord.ApplicationRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.carrecord.CarRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.orderprocessrecord.OrderProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.processrecord.ProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccesspercentage.ProductAccessPercentageDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable7.UserBaseTable7DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.wealthrecord.WealthRecordDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.applicationdeductrecord.ApplicationDeductRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.applicationrecord.ApplicationRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.carrecord.CarRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.housingresource.HousingResourceMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.orderprocessrecord.OrderProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.processrecord.ProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.product.ProductMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.user.MiniUserMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable7.UserBaseTable7Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.wealthrecord.WealthRecordMapper;
import cn.iocoder.yudao.module.handguard.service.notification.NotificationService;
import cn.iocoder.yudao.module.handguard.tool.CalculateUtils;
import cn.iocoder.yudao.module.handguard.tool.OrderUtils;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.handguard.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.handguard.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.handguard.convert.order.OrderConvert;
import cn.iocoder.yudao.module.handguard.dal.mysql.order.OrderMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.module.handguard.enums.ErrorCodeConstants.*;

/**
 * 订单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OrderServiceImpl implements OrderService {

    @Resource
    private NotificationService notificationService;

    @Resource
    private MiniUserMapper miniUserMapper;

    @Resource
    private ApplicationDeductRecordMapper deductRecordMapper;

    @Resource
    private ApplicationRecordMapper applicationRecordMapper;

    @Resource
    private OrderProcessRecordMapper orderProcessRecordMapper;

    @Resource
    private ProcessRecordMapper processRecordMapper;

    @Resource
    private WealthRecordMapper wealthRecordMapper;

    @Resource
    private HousingResourceMapper housingResourceMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private UserBaseTable7Mapper table7Mapper;



    @Override
    public Long createOrder(OrderCreateReqVO createReqVO) {
        // 插入
        OrderDO order = OrderConvert.INSTANCE.convert(createReqVO);
        //订单号
        String orderNumber = OrderUtils.getOrderCode(getLoginUser().getId().intValue());
        order.setOrderNo(orderNumber);
        //生成订单号
        orderMapper.insert(order);
        // 返回
        return order.getId();
    }

    @Override
    public void updateOrder(OrderUpdateReqVO updateReqVO) {
        // 校验存在
        validateOrderExists(updateReqVO.getId());
        // 更新
        OrderDO updateObj = OrderConvert.INSTANCE.convert(updateReqVO);
        orderMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrder(Long id) {
        // 校验存在
        validateOrderExists(id);
        // 删除
        orderMapper.deleteById(id);
    }

    private void validateOrderExists(Long id) {
        if (orderMapper.selectById(id) == null) {
            throw exception(ORDER_NOT_EXISTS);
        }
    }

    @Override
    public OrderDO getOrder(Long id) {
//        LambdaQueryWrapper<OrderDO> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(OrderDO::getOrderNo,id);
        return orderMapper.selectOne("order_no",id);
    }

    @Override
    public List<OrderDO> getOrderList(Collection<Long> ids) {
        return orderMapper.selectBatchIds(ids);
    }

    @Override
    public List<OrderDO> getOrderListByUserId(Long userId) {
        LambdaQueryWrapper<OrderDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDO::getUserId,userId);
        queryWrapper.orderByDesc(OrderDO::getCreateTime);
        List<OrderDO> orderDOList = orderMapper.selectList(queryWrapper);
        if (orderDOList.size()>0){
            orderDOList.forEach(o ->{
                //获取产品名称
                ProductDO productDO = productMapper.selectById(o.getProductId());
                if (productDO!=null){
                    o.setProductName(productDO.getProductName());
                }
            });
        }
        return orderDOList;
    }

    @Override
    public PageResult<OrderDO> getOrderPage(OrderPageReqVO pageReqVO) {
        return orderMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OrderDO> getOrderList(OrderExportReqVO exportReqVO) {
        return orderMapper.selectList(exportReqVO);
    }

    @Override
    public MemberUserBaseVO getOrderUserInfo(Long id) {
        MemberUserBaseVO memberUserBaseVO = new MemberUserBaseVO();
        ApplicationRecordDO  orderDO = applicationRecordMapper.selectById(id);
        if (orderDO!=null){
            Long userId = orderDO.getUserId();
            memberUserBaseVO = orderMapper.getUserInfoById(userId);
            //车辆信息
            LambdaQueryWrapper<UserBaseTable7DO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserBaseTable7DO::getUserId,userId);
            List<UserBaseTable7DO> carList = table7Mapper.selectList(wrapper);
            memberUserBaseVO.setCarList(carList);
        }
        return memberUserBaseVO;
    }

    @Override
    public int getMonthCjNumber(Long orderId) {
        int number = orderMapper.getMonthCjNumber(orderId);
        return number;
    }

    @Override
    public BigDecimal getMonthCjMoney(Long orderId) {
        return orderMapper.getMonthCjMoney(orderId);
    }

    @Override
    public List<String> getPerformanceStatistics(int year) {
        List<String> yearList = new ArrayList<>();
        PerformanceStatisticsResVO resVO = miniUserMapper.getPerformanceStatistics(year);
        if (resVO == null){
            for (int i=0;i<12;i++){
                yearList.add("0.0");
            }
        }else {
            yearList.add(resVO.getJan());
            yearList.add(resVO.getFeb());
            yearList.add(resVO.getMar());
            yearList.add(resVO.getApr());
            yearList.add(resVO.getMay());
            yearList.add(resVO.getJun());
            yearList.add(resVO.getJul());
            yearList.add(resVO.getAug());
            yearList.add(resVO.getSep());
            yearList.add(resVO.getOct());
            yearList.add(resVO.getNov());
            yearList.add(resVO.getDec());
        }
        return yearList;
    }


    @Override
    @Transactional
    public void updateOrderStateAndAmount(Long orderId, BigDecimal amount) {
        ApplicationRecordDO application = applicationRecordMapper.selectById(orderId);
        if(application == null){
            throw exception(ORDER_NOT_EXISTS);
        }else {
            if (application.getFlowN().equals("13") && application.getApplyState().equals("3")){
                throw exception(ORDER_ERROR_EXISTS);
            }
        }

        LocalDateTime time = LocalDateTime.now();

        //受理流程完，结单设置
        application.setFlowN("13");
        application.setApplyState("3");
        application.setPracticalAmount(amount);
        application.setPracticalTime(time);

        //更新用户申请贷款订单记录
        applicationRecordMapper.updateById(application);

        //删除审核记录
        processRecordMapper.deleteProcessRecordById(application.getId());

        //更新-用户申请贷款流程处理记录表
        ProcessRecordDO processRecordDO = new ProcessRecordDO();
        processRecordDO.setApplicationId(application.getId());
        processRecordDO.setIsFail("1");
        processRecordDO.setFlowN("13");
        processRecordDO.setUserId(application.getUserId());
        processRecordMapper.insert(processRecordDO);

        UserDO userDO = miniUserMapper.getUserInfo(application.getUserId());

        //查询提成明细记录
        ApplicationDeductRecordDO deductRecordDO = deductRecordMapper.selectOne("order_id",application.getId());
        if (deductRecordDO!=null){
                 //提成参数转换、计算
                ProductAccessPercentageDO percentageDO = new ProductAccessPercentageDO();
                BeanUtils.copyProperties(deductRecordDO,percentageDO);
                PercentageVO percentageVO = CalculateUtils.getDeduct(percentageDO,amount);

                //更新提成明细
                BeanUtils.copyProperties(percentageVO,deductRecordDO);
                deductRecordDO.setUpdateTime(LocalDateTime.now());
                deductRecordMapper.updateById(deductRecordDO);


                //用户返利倍率
                //用户返利财富值
                BigDecimal uWeal = userDO.getWealthValue();
                BigDecimal newUserWeal = uWeal.add(deductRecordDO.getClientRoyalty()).setScale(2, RoundingMode.HALF_UP);
                userDO.setWealthValue(newUserWeal);
                miniUserMapper.updateById(userDO);

                //插入财富值纪录
                WealthRecordDO userWealDO = new WealthRecordDO();
                userWealDO.setUserId(userDO.getId());
                userWealDO.setWealthValue(deductRecordDO.getClientRoyalty());
                userWealDO.setRemark("结单奖励");
                userWealDO.setIOrDecrease("1");
                wealthRecordMapper.insert(userWealDO);

                //推荐人财富值返利
                if (userDO.getReferrer()!=null){
                    userDO = miniUserMapper.getUserInfo(userDO.getReferrer());
                    if (userDO!=null){
                        BigDecimal weal = userDO.getWealthValue();
                        BigDecimal newWeal = weal.add(deductRecordDO.getReferrerRoyalty()).setScale(2, RoundingMode.HALF_UP);
                        userDO.setWealthValue(newWeal);
                        miniUserMapper.updateById(userDO);
                        //插入财富值纪录
                        WealthRecordDO wealthRecordDO = new WealthRecordDO();
                        wealthRecordDO.setUserId(userDO.getId());
                        wealthRecordDO.setWealthValue(deductRecordDO.getReferrerRoyalty());
                        wealthRecordDO.setRemark("结单奖励");
                        wealthRecordDO.setIOrDecrease("1");
                        wealthRecordMapper.insert(wealthRecordDO);
                        //if (userDO.getUserType().equals("1")){
                        //    //结单时，给用户推荐人进行返利财富值、如果业务员是推荐人则不返利
                        //}
                    }
            }
        }
        //发送结单消息
        notificationService.sendOrderNotification("贷款已审核完成，放款情况请联系相关工作人员！","test007",application.getUserId());

    }

}
